const { Service } = require('egg');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');

class SettingService extends Service {
  async updateDocxFile(file) {
    try {
      const targetDir = path.join(this.app.baseDir, 'app/public/docxFiles');
      await mkdirp(targetDir);

      // 删除已存在的docx文件
      const existingFiles = fs.readdirSync(targetDir);
      for (const existingFile of existingFiles) {
        if (existingFile.endsWith('.docx')) {
          fs.unlinkSync(path.join(targetDir, existingFile));
        }
      }

      // 保存新文件
      const targetPath = path.join(targetDir, 'legal.docx');
      const reader = fs.createReadStream(file.filepath);
      const writer = fs.createWriteStream(targetPath);

      await new Promise((resolve, reject) => {
        reader.pipe(writer);
        writer.on('finish', resolve);
        writer.on('error', reject);
      });
      return true;
    } catch (error) {
      return false;
    }
  }

  async getDocxFile() {
    try {
      const targetDir = path.join(this.app.baseDir, 'app/public/docxFiles');
      const targetPath = path.join(targetDir, 'legal.docx');
      const exists = fs.existsSync(targetPath);

      if (!exists) {
        return {
          exists: false,
          filePath: null,
          fileContent: null,
        };
      }

      const fileContent = await fs.promises.readFile(targetPath);
      return fileContent;
    } catch (error) {
      this.ctx.logger.error('获取文件失败:', error);
      return false;
    }
  }
}

module.exports = SettingService;
